namespace Admin2025.Domain.Entities.App;

public class AppUser : EntityBase
{
  public string Username { get; set; } = null!;
  public string Password { get; set; } = null!;

  // 方便对密码进行加密，防止被人破解
  public string Salt { get; set; } = null!;

  public string? AvatarUrl { get; set; }
  public string? Nickname { get; set; }
  public Guid? DepartmentId { get; set; }
  public AppDepartment? Department { get; set; }

  public ICollection<AppRole> Roles { get; set; } = new List<AppRole>();

  // 给用户分配角色（与数据库无直接关系）
  public void AssignRole(AppRole role)
  {
    if (!Roles.Contains(role))
      Roles.Add(role);
  }

  // 移除角色
  public void RemoveRole(AppRole role)
  {
    if (Roles.Contains(role))
      Roles.Remove(role);
  }

  // 判断是否拥有某种权限
  public bool HasPermission(string permissionCode)
  {
    return Roles.Any(r => r.HasPermission(permissionCode));
  }

  public void ChangePassword(string oldPwdHash, string newPwdHash)
  {
    if (Password != oldPwdHash) throw new Exception("原密码错误");
    Password = newPwdHash;
  }
  public void UpdateNickname(string nickname) => Nickname = nickname;
  public void UpdateAvatar(string avatarUrl) => AvatarUrl = avatarUrl;
  public void Enable() => IsActived = true;
  public void Disable() => IsActived = false;
}